package com.soledroid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.github.droidfu.widgets.WebImageView;
import com.soledroid.Model.Canteen;
import com.soledroid.Model.Dish;
import com.soledroid.Model.Stall;
import com.soledroid.Model.User;
import com.soledroid.Model.Checkin;
import com.soledroid.Model.Comment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.*;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;

public class ProfileActivity extends Activity{
	private LayoutInflater mInflater; 
	public static final int INVALID_ID = 0;
	
	public static final int COMMENT_TAB = 1;
	public static final int FRIEND_TAB = 2;
	protected int tabMode;
	
	protected TextView usernameTextView;
	protected TextView lastseenTextView;
	
	protected Button commentBtn;
	protected Button friendBtn;
	protected Button addFriendBtn;
	protected ImageView avatarView;
	
	protected ArrayList<Checkin> checkins;
	protected ArrayList<Comment> comments;
	protected ArrayList<User> friends;
	
	protected ListView lv;
	protected String android_id;
	protected int id;
	
	protected CommentAdapter commentAdapter;
	protected FriendAdapter friendAdapter;

	@Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.profile);
        
        mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        
        android_id = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
        
        try{
			id = getIntent().getExtras().getInt("id");
		} catch(Exception e){
			id = 1;
		}
		
        User user = fetchUserInfo(id);
        comments = fetchUserComments(id);
        friends = fetchUserFriends(id);
        
        avatarView = (ImageView) findViewById(R.id.avatarView);
        usernameTextView = (TextView) findViewById(R.id.usernameTextView);
        lastseenTextView = (TextView) findViewById(R.id.lastseenTextView);
        commentBtn = (Button) findViewById(R.id.commentBtn);
        friendBtn = (Button) findViewById(R.id.friendBtn);
        addFriendBtn = (Button) findViewById(R.id.addFriendBtn);
        
        if(isMyFriend(id)){
        	addFriendBtn.setVisibility(View.INVISIBLE);
        }
 
        lv = (ListView) findViewById(R.id.profileListView);
        
        commentAdapter = new CommentAdapter(this, R.layout.comment_list_entry, R.id.comment_content, comments);
        friendAdapter = new FriendAdapter(this, R.layout.comment_list_entry, R.id.comment_content, friends);
		ListView lv = (ListView) findViewById((R.id.profileListView));
		
		tabMode = COMMENT_TAB;
		lv.setAdapter(commentAdapter);

		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
					Comment comment = comments.get(position);
					
					Intent i = new Intent(getApplicationContext(), DishActivity.class);
					i.putExtra("id", comment.getToId());
					
					ProfileActivity.this.startActivity(i);
			}
		});
		
		commentBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				switchListView(COMMENT_TAB);
			}
		});
		
		friendBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				switchListView(FRIEND_TAB);
			}
		});
		
		addFriendBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost("http://soledroid.huytoan.com/friend");
				
				Integer myId = getSharedPreferences("me", MODE_PRIVATE).getInt("id", 0);

				try {
					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
					nameValuePairs.add(new BasicNameValuePair("user1_id", Integer.toString(id)));
					nameValuePairs.add(new BasicNameValuePair("user2_id", Integer.toString(myId)));
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

					// Execute HTTP Post Request
					ResponseHandler<String> responseHandler=new BasicResponseHandler();
					String responseBody = httpclient.execute(httppost, responseHandler);
					
					Toast.makeText(getApplicationContext(), "Friend added", Toast.LENGTH_LONG).show();
					
					addFriendBtn.setVisibility(View.INVISIBLE);
				} catch(Exception e){
					e.printStackTrace();
				}
			}
		});
        
        try {
        	if(user.getImage().equals("") || user.getImage().equals("null")) {
        		avatarView.setImageResource(R.drawable.default_picture);
        	} else{
        		avatarView.setImageDrawable(Drawable.createFromStream(Utils.fetchImage(user.getImage()), "src"));
        	}
        } catch (Exception e) {
            e.printStackTrace();
        } 
        
        usernameTextView.setText(user.getFullname());
        commentBtn.setText(comments.size() + " Comments");
        friendBtn.setText(friends.size() + " Friends");
	}
	
	public boolean isMyFriend(int id){
		Integer myId = getSharedPreferences("me", MODE_PRIVATE).getInt("id", 0);
		
		if(id == myId){
			return true;
		} else {
			
			try{
				URL url = new URL("http://soledroid.huytoan.com/id/" + myId + "/friends");
				URLConnection tc = url.openConnection();
				tc.setUseCaches(true);
				BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

				String line;
				while ((line = in.readLine()) != null) {
					JSONArray ja = new JSONArray(line);
					
					for (int i = 0; i < ja.length(); i++) {
						JSONObject jo = (JSONObject) ja.get(i);
						if(jo.getInt("id") == id){
							return true;
						}
					}
				}
			} catch(Exception e){
				e.printStackTrace();
				return false;
			}
		}
		
		return false;
	}
	
	public void switchListView(int tab){
		if(tab == FRIEND_TAB){
			tab = COMMENT_TAB;
			lv.setAdapter(friendAdapter);
			
			lv.setOnItemClickListener(null);
			lv.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					User friend = friends.get(position);
					
					Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
					i.putExtra("id", friend.getId());
					
					ProfileActivity.this.startActivity(i);
				}
			});
		} else if(tab == COMMENT_TAB){
			tab = FRIEND_TAB;
			lv.setAdapter(commentAdapter);
			
			lv.setOnItemClickListener(null);
			lv.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
						Comment comment = comments.get(position);
						
						Intent i = new Intent(getApplicationContext(), DishActivity.class);
						i.putExtra("id", comment.getToId());
						
						ProfileActivity.this.startActivity(i);
				}
			});
		}
	}
	
	public User fetchUserInfo(int userId)
	{
		User user = null;
		URL url;
		
		try {
			if(userId != INVALID_ID){
				url = new URL("http://soledroid.huytoan.com/user/" + userId);
			} else{
				url = new URL("http://soledroid.huytoan.com/udid/" + android_id);
			}
			
			URLConnection tc = url.openConnection();
			tc.setUseCaches(true);
			BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

			String line;
			while ((line = in.readLine()) != null) {
                JSONArray ja = new JSONArray(line);
 
                for (int i = 0; i < ja.length(); i++) {
                    JSONObject jo = (JSONObject) ja.get(i);
                    user = new User(jo.getInt("id"), jo.getString("username"), jo.getString("fullname"), jo.getString("image"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
        
        return user;
    }
	
	public ArrayList<Checkin> fetchUserCheckins(int userId)
	{
		ArrayList<Checkin> listItems = new ArrayList<Checkin>();

		try {
			URL url = new URL("http://soledroid.huytoan.com/user/" + userId + "/checkins");
			URLConnection tc = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

			String line;
			while ((line = in.readLine()) != null) {
                JSONArray ja = new JSONArray(line);
 
                for (int i = 0; i < ja.length(); i++) {
                    JSONObject jo = (JSONObject) ja.get(i);
                    Checkin checkin = new Checkin(jo.getInt("id"), jo.getInt("user_id"), jo.getInt("stall_id"));
                    listItems.add(checkin);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return listItems;
    }
	
	public ArrayList<Comment> fetchUserComments(int userId)
	{
		ArrayList<Comment> listItems = new ArrayList<Comment>();

		try {
			URL url = new URL("http://soledroid.huytoan.com/user/" + userId + "/comments");
			URLConnection tc = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

			String line;
			while ((line = in.readLine()) != null) {
                JSONArray ja = new JSONArray(line);
 
                for (int i = 0; i < ja.length(); i++) {
                    JSONObject jo = (JSONObject) ja.get(i);
                    Comment comment = new Comment(jo.getInt("id"), jo.getInt("type"), jo.getString("comment"),
                    							jo.getInt("rating"), jo.getInt("user_id"), jo.getInt("to_id"));
                    listItems.add(comment);
                }
            }
        } catch(Exception e){
        	e.printStackTrace();
        }
        return listItems;
    }
	
	public ArrayList<User> fetchUserFriends(int userId)
	{
		ArrayList<User> listItems = new ArrayList<User>();

		try {
			URL url = new URL("http://soledroid.huytoan.com/user/" + userId + "/friends");
			URLConnection tc = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

			String line;
			while ((line = in.readLine()) != null) {
                JSONArray ja = new JSONArray(line);
 
                for (int i = 0; i < ja.length(); i++) {
                    JSONObject jo = (JSONObject) ja.get(i);
                    User friend = new User(jo.getInt("id"), jo.getString("username"), jo.getString("fullname"),
                    							jo.getString("image"));
                    listItems.add(friend);
                }
            }
        } catch(Exception e){
        	e.printStackTrace();
        }
        return listItems;
    }
	
	public void uploadNewProfilePicture(){
		
	}
	
	private class CommentAdapter extends ArrayAdapter<Comment> {
		public CommentAdapter(Context context, int resource, int textViewResourceId, List<Comment> objects) {
			super(context, resource, textViewResourceId, objects);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {   
			ViewHolder holder = null;
			RatingBar ratingBar = null;
			TextView commentView = null;
			WebImageView avatarView = null;
			Comment rowData = getItem(position);

			if(convertView == null) {
				convertView = mInflater.inflate(R.layout.comment_list_entry, null);
				holder = new ViewHolder(convertView);
				convertView.setTag(holder);
			}

			holder = (ViewHolder) convertView.getTag();

			ratingBar = holder.getRatingBar();
			ratingBar.setRating((float)(rowData.getRating()));

			commentView = holder.getCommentView();
			commentView.setText(rowData.getComment());


			avatarView = holder.getImageView();
			try {
				avatarView.setImageUrl("http://soledroid.huytoan.com/dish/" + rowData.getToId() + "/picture");
				avatarView.loadImage();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return convertView;
		}
	}
	
	private class FriendAdapter extends ArrayAdapter<User> {
		public FriendAdapter(Context context, int resource, int textViewResourceId, List<User> objects) {
			super(context, resource, textViewResourceId, objects);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {   
			ViewHolder holder = null;
			RatingBar ratingBar = null;
			TextView commentView = null;
			WebImageView avatarView = null;
			User rowData = getItem(position);

			if(convertView == null) {
				convertView = mInflater.inflate(R.layout.comment_list_entry, null);
				holder = new ViewHolder(convertView);
				convertView.setTag(holder);
			}

			holder = (ViewHolder) convertView.getTag();

			ratingBar = holder.getRatingBar();
			ratingBar.setVisibility(View.INVISIBLE);

			commentView = holder.getCommentView();
			commentView.setText(rowData.getFullname());


			avatarView = holder.getImageView();
			try {
				avatarView.setImageUrl(rowData.getImage());
				avatarView.loadImage();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return convertView;
		}
	}

	private class ViewHolder {
		private View mRow;
		private RatingBar mRatingBar = null;
		private TextView mCommentView = null;
		private WebImageView mImageView = null; 

		public ViewHolder(View row) {
			mRow = row;
		}

		public RatingBar getRatingBar() {
			if(mRatingBar == null) {
				mRatingBar = (RatingBar) mRow.findViewById(R.id.comment_rating);
			}

			return mRatingBar;
		}

		public TextView getCommentView() {
			if(mCommentView == null) {
				mCommentView = (TextView) mRow.findViewById(R.id.comment_content);
			}
			return mCommentView;
		}  

		public WebImageView getImageView() {
			if(mImageView == null){
				mImageView = (WebImageView) mRow.findViewById(R.id.comment_img);
			}
			return mImageView;
		}
	}
	 @Override
		public boolean onCreateOptionsMenu(Menu menu) {
			boolean result = super.onCreateOptionsMenu(menu);
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.menu, menu);
			return result;
		}
	    
	    @Override
		public boolean onOptionsItemSelected(MenuItem item) {
			Intent i;
			switch(item.getItemId()) {
			case R.id.menu_search:
				onSearchRequested();
				return true;
			case R.id.menu_preferences:
				showPreferences();
				return true;
			}
			return super.onOptionsItemSelected(item);
		}
	    
	    private void showPreferences() {
			Intent i = new Intent(this, SettingsActivity.class);
			startActivity(i);
		}
}
